package com.bigfish.gbs.controller;

import com.bigfish.gbs.dto.Result;
import com.bigfish.gbs.entity.Resource;
import com.bigfish.gbs.entity.Role;
import com.bigfish.gbs.enums.ResultEnum;
import com.bigfish.gbs.service.ResourceService;
import com.bigfish.gbs.service.RoleService;
import com.bigfish.gbs.util.ResultUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author Joycessh
 * @Description 角色相关
 * @Date 12/15/18 2:39 PM
 */
@Api(value = "角色管理", description = "角色管理相关的crud接口")
@RestController
@RequestMapping("/role")
public class RoleController extends BasicAction {

    private static final Logger LOGGER = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;

    /**
     * 获取所有的角色信息
     * @author Joycessh
     * @param currentPage
	 * @param pageSize
     * @return com.bigfish.gbs.dto.Result
     * @date 12/15/18 10:44 PM
     */
    @ApiOperation(value = "获取角色LIST", httpMethod = "GET")
    @GetMapping("/{currentPage}/{pageSize}")
    public Result getRoles(@PathVariable Integer currentPage,
                           @PathVariable Integer pageSize) {

        PageHelper.startPage(currentPage, pageSize);
        List<Role> roles = roleService.getRoleList();
        PageInfo pageInfo = new PageInfo(roles);
        return ResultUtil.retFormat(ResultEnum.SUCCESS).addData("roles", pageInfo);
    }

    /**
     * 添加角色
     * @author Joycessh
     * @param role
     * @return com.bigfish.gbs.dto.Result
     * @date 12/15/18 10:45 PM
     */
    @ApiOperation(value = "添加角色", httpMethod = "POST")
    @PostMapping("")
    public Result addRole(@RequestBody Role role) {

        boolean flag = roleService.addRole(role);
        if (flag) {
            return ResultUtil.retFormat(ResultEnum.SUCCESS);
        } else {
            return ResultUtil.retFormat(ResultEnum.FAIL);
        }
    }

    /**
     * 更新角色
     * @author Joycessh
     * @param role
     * @return com.bigfish.gbs.dto.Result
     * @date 12/15/18 10:45 PM
     */
    @ApiOperation(value = "更新角色", httpMethod = "PUT")
    @PutMapping("")
    public Result updateRole(@RequestBody Role role) {

        boolean flag = roleService.updateRole(role);
        if (flag) {
            return ResultUtil.retFormat(ResultEnum.SUCCESS);
        } else {
            return ResultUtil.retFormat(ResultEnum.FAIL);
        }
    }

    /**
     * 删除角色
     * @author Joycessh
     * @param roleId
     * @return com.bigfish.gbs.dto.Result
     * @date 12/15/18 10:46 PM
     */
    @ApiOperation(value = "根据角色ID删除角色", httpMethod = "DELETE")
    @DeleteMapping("/{roleId}")
    public Result deleteRoleByRoleId(@PathVariable Integer roleId) {

        boolean flag = roleService.deleteRoleByRoleId(roleId);
        if (flag) {
            return ResultUtil.retFormat(ResultEnum.SUCCESS);
        } else {
            return ResultUtil.retFormat(ResultEnum.FAIL);
        }
    }

    @ApiOperation(value = "获取角色(roleId)所被授权的API资源")
    @GetMapping("/api/{roleId}/{currentPage}/{pageSize}")
    public Result getRestApiExtendByRoleId(@PathVariable Integer roleId,
                                           @PathVariable Integer currentPage,
                                           @PathVariable Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Resource> resources = resourceService.getAuthorityApisByRoleId(roleId);
        PageInfo pageInfo = new PageInfo(resources);
        return ResultUtil.retFormat(ResultEnum.SUCCESS).addData("authRes", pageInfo);
    }


    @ApiOperation(value = "获取角色(roleId)未被授权的API资源")
    @GetMapping("/api/-/{roleId}/{currentPage}/{pageSize}")
    public Result getRestApiByRoleId(@PathVariable Integer roleId,
                                     @PathVariable Integer currentPage,
                                     @PathVariable Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Resource> resources = resourceService.getNotAuthorityApisByRoleId(roleId);
        PageInfo pageInfo = new PageInfo(resources);
        return ResultUtil.retFormat(ResultEnum.SUCCESS).addData("restApis", pageInfo);
    }

    @ApiOperation(value = "授权资源给角色",httpMethod = "POST")
    @PostMapping("/authority/resource")
    public Result authorityRoleResource(HttpServletRequest request) {

        Map<String,String> map = getRequestBody(request);
        int roleId = Integer.parseInt(String.valueOf(map.get("roleId")));      // 虽然map中取出value是 String ，但其实质是 Integer
        System.out.println(roleId);                                            // 故在将其强制转为 Integer 时会出现强制类型转换的异常
        int resourceId = Integer.valueOf(String.valueOf(map.get("resourceId")));     // 解决办法： 可使用toString() / String.valueOf() 将其先转为 String 再转为需要的数据类型
        boolean flag = roleService.authorityRoleResource(roleId,resourceId);
//        shiroFilterChainManager.reloadFilterChain();
        return flag ? ResultUtil.retFormat(ResultEnum.SUCCESS) : ResultUtil.retFormat(ResultEnum.FAIL);
    }

    @ApiOperation(value = "删除对应的角色的授权资源",httpMethod = "DELETE")
    @DeleteMapping("/authority/resource/{roleId}/{resourceId}")
    public Result deleteAuthorityRoleResource(@PathVariable Integer roleId,
                                              @PathVariable Integer resourceId ) {
        boolean flag = roleService.deleteAuthorityRoleResource(roleId,resourceId);
//        shiroFilterChainManager.reloadFilterChain();
        return flag ? ResultUtil.retFormat(ResultEnum.SUCCESS) : ResultUtil.retFormat(ResultEnum.FAIL);
    }
}
